package edu.sias.controller;

import edu.sias.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/user/editPsw")
public class UserEditPswServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //修改密码时，需要校验下原密码是否正确
        String name = (String) request.getSession()
                .getAttribute("name");
        String psw = request.getParameter("psw");

        //调用之前设定好的登陆查询操作，帮助我们校验密码
        UserService userService = new UserService();
        boolean result = userService.loginUser(name, psw);
        if(result){
            //如果旧密码校验通过，修改密码
            String newPsw = request.getParameter("newPsw");
            userService.editPsw(name,newPsw);
            //使当前session失效，保证数据一致性
            request.getSession().invalidate();
            response.sendRedirect("/login.jsp");
        }else {
            //如果旧密码校验不通过，重新返回修改页面输入
            String error = "输入的原密码错误";
            request.setAttribute("error",error);
            request.getRequestDispatcher("/editPsw.jsp")
                    .forward(request,response);
        }

    }


}
